package com.aaa.controller;

import com.aaa.entity.ResponseDto;
import com.aaa.entity.Staff;
import com.aaa.service.StaffService;
import com.aaa.service.impl.StaffServiceImpl;
import com.google.gson.Gson;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {

    private StaffService staffService;

    @Override
    public void init() throws ServletException {
        //一定要把service写在init()方法中，这样初始化一次
        //如果写在doGet或doPost里面每次调用都会创建，耗费时间
        staffService = new StaffServiceImpl();
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
            IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,
            IOException {
        String staffId = request.getParameter("loginName");
        String password = request.getParameter("loginPwd");

        ResponseDto responseDto = new ResponseDto();

        try {
            Staff staff = staffService.login(staffId, password);
            if (staff != null) {
                responseDto.setStatus(ResponseDto.SUCCESS_CODE);
                responseDto.setData(staff);
                responseDto.setMessage("请求成功");

            } else {
                responseDto.setStatus(ResponseDto.FAILURE_CODE);
                responseDto.setMessage("用户不存在");
            }
        } catch (Exception e) {
            e.printStackTrace();
            responseDto.setStatus(ResponseDto.FAILURE_CODE);
            responseDto.setMessage(e.getMessage());
            responseDto.setMessage("请求失败");
        }

        response.getWriter().write(new Gson().toJson(responseDto));

    }
}
